/**
* [insertInfoTpl 插入 html信息]
* @param  {[type]} data [渲染所需的数据]
* @param  {[type]} dom  [加入页面中的哪个DOM节点]
* @param  {[type]} tpl  [模板节点ID]
* @return {[type]}      [description]
*/
function insertTpl(data, dom, tpl) {
    var infoTpl = tpl.html()
    var compiled = _.template(infoTpl)
    var html = ''
    _.forEach(data, function(item, index) {
        item.index = index + 1
        // console.log(item, index)
        html += compiled(item)
    })
    dom.append($(html))
}

function genSeriesData(legends) {
    return _.map(legends, function(item, index) {
        return {
            name: item,
            value: randomRangeNum(100, 10000)
        }
    })
}

function locationTime() {
	var date = new Date()
	var year = date.getFullYear()
	var month = trimTime( date.getMonth() + 1 )
	var day = trimTime( date.getDate() )
	var hour = trimTime( date.getHours() )
	var minutes = trimTime( date.getMinutes() )
	var seconds = trimTime( date.getSeconds() )

	var time = year + '-' + month + '-' + day + ' ' + hour + ':' + minutes + ':' + seconds

	return time;
}

function trimTime(t) {
	return t = t > 9 ? t : '0' + t 
}

// 生成随机数字
function randomNum(num) {
	num = num || 1000
	return Math.ceil(Math.random() * num)
}

function genData(length) {
	return Array.from({length},  item => randomRangeNum(100, 6000))
}
		
function randomRangeNum(min, max) {
	return Math.floor( ( Math.random() * (max - min)) + min )
}

function copyArray(source, array) {
	var index = -1
	var length = source.length

	array || (array = new Array(length))
	while (++index < length) {
		array[index] = source[index]
	}
	return array
}

// 随机排列
function shuffle(array) {
  	var length = array == null ? 0 : array.length
	if (!length) {
		return []
	}
	var index = -1
	var lastIndex = length - 1
	var result = copyArray(array)
	while (++index < length) {
		var rand = index + Math.floor(Math.random() * (lastIndex - index + 1))
		var value = result[rand]
		result[rand] = result[index]
		result[index] = value
	}
	return result
}


function deepClone(source) {
    if (!source && typeof source !== 'object') {
        throw new Error('error arguments', 'shallowClone')
    }
    var targetObj = source.varructor === Array ? [] : {}
    for (var keys in source) {
        if (source.hasOwnProperty(keys)) {
            if (source[keys] && typeof source[keys] === 'object') {
                targetObj[keys] = source[keys].varructor === Array ? [] : {}
                targetObj[keys] = deepClone(source[keys])
            } else {
                targetObj[keys] = source[keys]
            }
        }
    }
    return targetObj
}

Date.prototype.Format = function (fmt) {
    var o = {
        "YYYY+": this.getFullYear(), //月份
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) {
    	fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
        	fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
}

var get7Days = function(num, format){
	num = num || 0
	if(typeof(num) === 'string') {
		format = num
		num = 0
	} else {
		format = format || 'yyyy/MM/dd'
	}
	
    var arr = new Array()
    for (var i = num * 7 + 1;i < (num+1)*7 + 1;i++){
        var currDate = new Date()
        arr.push(new Date(currDate.getTime() - i * 1000 * 60 * 60 * 24).Format(format))
    }
    arr.reverse()
    return arr;
}


function getLegend(data) {
	return data.map( item => item.name)
}

function sum(data) {
	return data.reduce( (pre, item) => (pre + item.value), 0)
}

function getPrecent(data, index) {
	// console.log(data[index].value , sum(data))
	return (data[index].value / sum(data) * 100).toFixed(2) + '%'
}


/**
 * @param {echarts object} pieChart     echarts.init后的变量
 * @param {object} data                 数据
 * @param {object} pieOption            初始配置
 * @param {number} changeSeriesIndex    需要改变的series中pie的下标  默认值为 2
 * @param {number} showLabelSeriesIndex 展示内容的series中的pie的下标 默认值为 3
 * @param {number} time                 轮播间隔时间，默认值2000
 */
var pieAutoShow = function (pieChart, data, pieOption, changeSeriesIndex, showLabelSeriesIndex, time) {
    var pieIndex = 0,
        timer = null,
    changeSeriesIndex = changeSeriesIndex || 2
    showLabelSeriesIndex = showLabelSeriesIndex || 3
    time = 2000
    function autoshow() {
        pieIndex = pieIndex === data.length - 1 ? 0 : ++pieIndex
        
        var _d = data[pieIndex]
        for (var i = 0; i < data.length; i++){
            if (i != pieIndex){
                pieOption.series[changeSeriesIndex].data[i]['selected'] = false
            }else{
                pieOption.series[changeSeriesIndex].data[i]['selected'] = true
            }
        }
        pieOption.series[showLabelSeriesIndex].data[0].label.normal.formatter =  getPrecent(data, pieIndex)
        pieOption.series[showLabelSeriesIndex].data[1].label.normal.formatter = "\n" + _d.name
        pieChart.setOption(pieOption)
    }   
    timer = setInterval(autoshow, time)
    pieChart.on('mouseover', function(params) {
        clearInterval(timer)
        pieIndex = params.dataIndex - 1
        autoshow()
    })
    pieChart.on('mouseout', function(params) {
        timer = setInterval(autoshow, time)
    })  
}


function chartInit(el, chartOpt) {
    var chart = echarts.init($(el)[0])
    chart.setOption(chartOpt)
    window.addEventListener("resize", function () {
        chart.resize()
    })
}

function sort(data, flag) {
    return data.sort(function(a, b) {
        return flag ? a > b : a < b
    })
}